<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use zgldh\QiniuStorage\QiniuStorage;
use App\Article;
use App\Type;
use Input;
use DB;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //获取所有数据
        $datas = Article::select('aid','istop','isadd','title','status')->paginate('2');
        return view('admin.article.index',compact('datas'));

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //返回页面
        $datas = Type::select('typeid','typename')->get();
        return view('admin.article.add',compact('datas'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //进行表单验证
        $this -> validate($request,[
            'istop'=>'required|between:1,4',
            'title'=>'required|max:200',
            'keyword'=>'max:200',
            'description'=>'required|max:250',
        ],[
            'istop.required'=>'置顶等级需要填写',
            'istop.between'=>'需要是1-4',
            'title.required'=>'标题不能为空',
            'title.max'=>'标题长度过长',
            'keyword.max'=>'关键字过多',
            'description.required'=>'描述不能为空',
            'description.max'=>'描述字数过多',
        ]);
        //然后接受数据
        $typeid = trim(Input::get('typeid'));
        $istop = trim(Input::get('istop'));
        $title = Input::get('title');
        $keyword = Input::get('keyword');
        $isadd = Input::get('isadd');
        $description = Input::get('description');
        $sort = Input::get('sort');
        $status = Input::get('status');
        $content = Input::get('content');
        $senddate = time();
        //先判断是否有封面图片
        if(!($request ->hasFile('coverpic'))){
            //返回
            return back() -> with(['info'=>'请添加封面图片']);
        }else{
            //将图片存入七牛
            $file = Input::file('coverpic');
            //获取后缀名
            $extension = strtolower($file->getClientOriginalExtension());
            if(!in_array($extension,['png','jpg']))
            return back() -> with(['info'=>'封面图片需要时png或者jpg类型']);
            //获取扩展名
            $clientname = $file -> getClientOriginalName();
            $disk = QiniuStorage::disk('qiniu');
            $coverpic = 'article/coverpic/'.md5(date('Y-m-d H:i:s').$clientname).".".$extension;
            //上传到七牛
            $bool = $disk -> put($coverpic,file_get_contents($file -> getRealPath()));
            if($bool){
                //将数据插入数据库
                $res = Article::create(['typeid'=>$typeid,'istop'=>$istop,'isadd'=>$isadd,'title'=>$title,'coverpic'=>$coverpic,'description'=>$description,'keyword'=>$keyword,'content'=>$content,'senddate'=>$senddate,'sort'=>$sort,'status'=>$status]);
            if($res) return back() -> with(['info'=>'数据添加成功']);
            return back() -> with(['info'=>'数据添加失败']);
            }else{
                return back() -> with('存入七牛失败');
            }
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //根据id查看所有信息啥
        $datas = DB::table('article')
                ->select('article.*','type.typename')
                ->join('type','article.typeid','=','type.typeid')
                ->where('article.aid',$id)
                ->first();
        return view('admin.article.show',compact('datas'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //获取分类数据
        $datas = Article::where('aid',$id)->first();
        $tdatas = Type::select('typeid','typename')->get();
        return view('admin.article.edit',compact('datas','tdatas'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //进行表单验证
        $this -> validate($request,[
            'istop'=>'required|between:1,4',
            'title'=>'required|max:200',
            'keyword'=>'max:200',
            'description'=>'required|max:250',
        ],[
            'istop.required'=>'置顶等级需要填写',
            'istop.between'=>'需要是1-4',
            'title.required'=>'标题不能为空',
            'title.max'=>'标题长度过长',
            'keyword.max'=>'关键字过多',
            'description.required'=>'描述不能为空',
            'description.max'=>'描述字数过多',
        ]);
        //然后接受数据
        $typeid = trim(Input::get('typeid'));
        $istop = trim(Input::get('istop'));
        $title = Input::get('title');
        $keyword = Input::get('keyword');
        $isadd = Input::get('isadd');
        $description = Input::get('description');
        $sort = Input::get('sort');
        $status = Input::get('status');
        $content = Input::get('content');
        $oldcoverpic = Input::get('oldcoverpic');
        //判断是否有图片
        if(!($request -> hasFile('file'))){
            //执行更新
        $res = Article::where('aid',$id)->update(['typeid'=>$typeid,'istop'=>$istop,'isadd'=>$isadd,'title'=>$title,'description'=>$description,'keyword'=>$keyword,'content'=>$content,'sort'=>$sort,'status'=>$status]);
        if($res)
        return back() -> with(['info'=>'更新成功']);
        return back() -> with(['info'=>'更新失败']);
        }else{
            $file = Input::file('file');
            $extension = $file -> getClientOriginalExtension();
            $extension = strtolower($extension);
            if(!in_array($extension,['png','jpg']))
            return back() -> with(['info'=>'需要png类型或者jpg类型']);
        //获取其他扩展名
        $clientName = $file -> getClientOriginalName();
        $disk = QiniuStorage::disk('qiniu');
        //删除七牛图片,然后再存入图片
        $newcoverpic = 'article/coverpic/'.md5(date('Y-m-d H:i:s').$clientName).".".$extension;
        $bool = $disk -> put($newcoverpic,file_get_contents($file->getRealPath()));
        if($bool){
            //获取内容
            $oldcontent = Article::where('aid',$id)->value('content');
            $pattern = "/<[img|IMG].*?src=[\'|\"].*?(article(.*?)(?:[\.gif|\.jpg|\.png|\/jpeg]))[\'|\"].*?[\/]?>/";
            preg_match_all($pattern, $content, $match);
            //循环删除
            foreach ($match['1'] as $k => $v) {
                $bool = $disk->delete($v);
            }
            //将数据插入数据库
             $res = Article::where('aid',$id)->update(['typeid'=>$typeid,'istop'=>$istop,'isadd'=>$isadd,'title'=>$title,'coverpic'=>$newcoverpic,'description'=>$description,'keyword'=>$keyword,'content'=>$content,'sort'=>$sort,'status'=>$status]);

              $delete = $disk->delete($oldcoverpic);
              if($delete)
              return back() -> with(['info' => '更新成功']);
              return back() -> with(['info' => '更新成功，原图片删除失败,地址是:'.$oldcoverpic]);

        }else{
            return back()->with(['info' => '数据库更新失败，图片已经传到七牛云,图片地址:是'.$newcoverpic]);
        }
    }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
         //获取内容里面的图片；利用正则删除
         $datas = Article::where('aid',$id)->first();
         //当前的文章的封面图片的地址
        $coverpic = $datas['coverpic'];
         //正则提取对应的图片
         $res = Article::where('aid',$id)->delete();
         if($res){
            $disk = QiniuStorage::disk('qiniu');
             $content = $datas['content'];
             $pattern = "/<[img|IMG].*?src=[\'|\"].*?(article(.*?)(?:[\.gif|\.jpg|\.png|\/jpeg]))[\'|\"].*?[\/]?>/";
             preg_match_all($pattern,$content,$match);
             //循环删除
             foreach ($match['1'] as $k=>$v){
                $bool = $disk -> delete($v);
             }
            $bool = $disk -> delete($datas['coverpic']);
            if($bool){
                return Response() -> json(['status'=>'success','msg'=>'删除成功']);
            }else{
                return Response() -> json(['status'=>'error','msg'=>'删除七牛图片失败地址:'.$coverpic]);
            }
          
         }else{
                return Response() -> json(['status'=>'error','msg'=>'删除失败']);
         }
    }
}
